import android.util.Log
import io.ktor.client.call.body
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.ServerResponseException
import ktor.models.ApiResponse

class ApiError(override val message: String? = null, val code: Int? = null) : Exception()

suspend inline fun <reified T> sendRequest(block: () -> T): Result<T> {
    return try {
        Result.success(block())
    } catch (e: ClientRequestException) {
        e.printStackTrace()
        Log.d("DATA", "${e.response.body<ApiResponse<T>>()}")
        return Result.failure(
            ApiError(
                e.response.body<ApiResponse<T>>().message,
                e.response.status.value
            )
        )
    } catch (e: ServerResponseException) {
        e.printStackTrace()
        return Result.failure(
            ApiError(
                e.response.body<ApiResponse<T>>().message,
                e.response.status.value
            )
        )
    } catch (e: Exception) {
        e.printStackTrace()
        return Result.failure(ApiError("Ошибка запроса"))
    }
}